package com.gitee.somenvm.ninerpgitem.compat.attribute

import ac.github.oa.api.OriginAttributeAPI
import ac.github.oa.internal.core.attribute.AbstractAttribute
import ac.github.oa.internal.core.attribute.AttributeManager
import org.bukkit.Bukkit
import org.bukkit.entity.LivingEntity
import org.bukkit.inventory.ItemStack
import taboolib.platform.util.hasLore
import java.util.*

/**
 *
 * @author  SomeNvM
 * @date  2022/12/12 17:48
 */
object OriginAttributeBridge : AttributeBridge {
    override fun addAttributes(uuid: UUID, reads: List<String>) {
        addAttributes(UUID.randomUUID().toString(), uuid, reads)
    }

    override fun addAttributes(source: String, uuid: UUID, reads: List<String>) {
        val data = OriginAttributeAPI.loadList(reads)
        OriginAttributeAPI.setExtra(uuid, source, data)
    }

    override fun update(entity: LivingEntity) {
        OriginAttributeAPI.callUpdate(entity)
    }

    override fun update(uuid: UUID) {
        this.update(Bukkit.getEntity(uuid) as? LivingEntity ?: return)
    }

    override fun removeAttributes(uuid: UUID, source: String) {
        OriginAttributeAPI.removeExtra(uuid, source)
    }

    override fun getAttributeValue(uuid: UUID, keyword: String): Double {
        val entity = Bukkit.getEntity(uuid) as? LivingEntity ?: return 0.0
        val index = AttributeManager.usableAttributes.values.find {
            (it as AbstractAttribute).entries.flatMap { entry -> entry.getKeywords() }.contains(keyword)
        }?.getPriority() ?: -1

        if (index != -1) {
            val entry =
                (AttributeManager.getAttribute(index) as AbstractAttribute).entries.firstOrNull { keyword in it.getKeywords() }
                    ?: return 0.0
            val attributeData = OriginAttributeAPI.getAttributeData(entity)
            val value = attributeData.getArrayData(index)[entry.index]
            return value.get(0)
        }
        return 0.0
    }

    override fun getAttributeValue(list: MutableList<String>, keyword: String): Number {
        val index = AttributeManager.usableAttributes.values.find {
            (it as AbstractAttribute).entries.flatMap { entry -> entry.getKeywords() }.contains(keyword)
        }?.getPriority() ?: return 0.0

        val entry =
            (AttributeManager.getAttribute(index) as AbstractAttribute).entries.find { keyword in it.getKeywords() }
                ?: return 0.0
        val attributeData = OriginAttributeAPI.loadList(list)
        val value = attributeData.getArrayData(index)[entry.index]
        return value.get(0)

    }

    override fun getAttributeValue(itemStack: ItemStack, keyword: String): Number {
        if (itemStack.hasLore()) {
            val list = itemStack.itemMeta?.lore!!
            return getAttributeValue(list, keyword)
        }
        return 0.0
    }
}